package com.jzo2o.customer.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.expcetions.DBException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.common.utils.StringUtils;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {

        List<AddressBook> addressBooks = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getCity, city)
                .list();
        if(CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }


    /**
     * 新增地址
     *
     * @param dto
     */
    @Override
    public void creat(AddressBookUpsertReqDTO dto) {
        //判断参数
        if (ObjectUtil.isEmpty(dto)){
            throw new BadRequestException("参数错误");
        }

        AddressBook addressBook = BeanUtils.copyBean(dto, AddressBook.class);
        String location = dto.getLocation();
        if (StringUtils.isNotBlank(location)) {
            String[] strings = StringUtils.splitToArray(location, ",");
            addressBook.setLon(Double.parseDouble(strings[0]));
            addressBook.setLat(Double.parseDouble(strings[1]));
        }
        //如果添加的是默认地址,取消之前的默认地址
        if (dto.getIsDefault() == 1 ){
            this.lambdaUpdate()
                    .eq(AddressBook::getUserId, UserContext.currentUserId())
                    .eq(AddressBook::getIsDefault,1)
                    .set(AddressBook::getIsDefault, 0)
                    .update();
        }

        addressBook.setUserId(UserContext.currentUserId());
        boolean save = save(addressBook);
        if (!save){
            throw new DBException("新增地址失败");
        }
    }


    /**
     * 地址的分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult pageQuery(AddressBookPageQueryReqDTO dto) {

        //判断参数
        if (ObjectUtil.isEmpty(dto)){
            throw new BadRequestException("参数错误");
        }
        Page<AddressBook> addressBookPage = PageUtils.parsePageQuery(dto, AddressBook.class);
        Page<AddressBook> page = this.lambdaQuery()
                .eq(AddressBook::getUserId, UserContext.currentUserId())
                .orderBy(StringUtils.isNotBlank(dto.getOrderBy1()), dto.getIsAsc1(), AddressBook::getIsDefault)
                .orderBy(StringUtils.isNotBlank(dto.getOrderBy2()), dto.getIsAsc2(), AddressBook::getUpdateTime)
                .page(new Page<>(dto.getPageNo(), dto.getPageSize()));

        return PageUtils.toPage(page, AddressBookResDTO.class);
    }

    /**
     * 修改地址
     *
     * @param dto
     */
    @Override
    public void updatebyId(AddressBookUpsertReqDTO dto,Long id) {
        //判断参数
        if (ObjectUtil.isEmpty(dto)){
            throw new BadRequestException("参数错误");
        }

        AddressBook addressBook = BeanUtils.copyBean(dto, AddressBook.class);

        String location = dto.getLocation();
        if (StringUtils.isNotBlank(location)) {
            String[] strings = StringUtils.splitToArray(location, ",");
            addressBook.setLon(Double.parseDouble(strings[0]));
            addressBook.setLat(Double.parseDouble(strings[1]));
        }
        addressBook.setId(id);
        boolean update =this.updateById(addressBook);
        if (!update){
            throw new DBException("修改地址失败");
        }
    }

    /**
     * 批量删除地址
     *
     * @param ids
     */
    @Override
    @Transactional
    public void deletebatch(List<String> ids) {
        if (CollUtils.isEmpty(ids)){
            throw new BadRequestException("参数错误");
        }
        boolean removeByIds = removeByIds(ids);
        if (!removeByIds){
            throw new DBException("删除地址失败");
        }
    }

    /**
     * 设置为默认地址
     *
     * @param flag
     * @param id
     */
    @Override
    @Transactional
    public void toDefault(Integer flag, Long id) {
        //判断参数
        if (ObjectUtil.isEmpty(flag) || ObjectUtil.isEmpty(id)){
            throw new BadRequestException("参数错误");
        }
        //设置默认参数
        if (flag == 1){
            //判断是否存在
            AddressBook addressBook = this.lambdaQuery().eq(AddressBook::getId, id).one();
            if (ObjectUtils.isNotEmpty(addressBook) ) {
                //同时将别的地址设置为非默认
                this.lambdaUpdate()
                        .eq(AddressBook::getUserId, UserContext.currentUserId())
                        .eq(AddressBook::getIsDefault,1)
                        .set(AddressBook::getIsDefault, 0)
                        .update();
                addressBook.setIsDefault(flag);
                this.updateById(addressBook);
            }else {
                throw new BadRequestException("地址不存在");
            }

        }
    }


    /**
     * 查询默认地址
     *
     * @return
     */
    @Override
    public AddressBook findDefault() {
        AddressBook addressBook = this.lambdaQuery()
                .eq(AddressBook::getUserId, UserContext.currentUserId())
                .eq(AddressBook::getIsDefault,1)
                .one();
        return addressBook;
    }
}
